package com.cloud.advice;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.enums.SecurityEnum;
import com.cloud.exception.ValidateException;
import com.cloud.pojo.sys.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理Controller层全局异常处理
 *
 * @since 2020-12-24 09:10:08
 */
@ControllerAdvice
public class GlobalExceptionController {

    private static Logger LOG = LoggerFactory.getLogger(GlobalExceptionController.class);

    /**
     * 捕获入参校验异常
     */
    @ExceptionHandler(ValidateException.class)
    public ResponseEntity<Result> handleCustomException(ValidateException ex) {
        GlobalExceptionController.LOG.error("哎呦！异常:" + ex.getErrorMsg());
        return new ResponseEntity(Result.createFail(ex.getErrorMsg()), HttpStatus.OK);
    }

    /**
     * 捕获访问权限异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity handleCustomException() {
        return new ResponseEntity(Result.createFail(SecurityEnum.AUTHORIZE_FAILURE.getCode(), SecurityEnum.AUTHORIZE_FAILURE.getDesc()), HttpStatus.OK);
    }

    /**
     * 捕获参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Result> handleValidateException(BindException ex, BindingResult results) {
        List<JSONObject> errorList = new ArrayList<>();
        if (results.hasErrors()) {
            List<FieldError> errors = results.getFieldErrors();
            JSONObject filed = new JSONObject();
            errors.forEach(error -> {
                filed.put(error.getField(), error.getDefaultMessage());
                errorList.add(filed);
            });
        }
        return new ResponseEntity(Result.createFail(JSONUtil.toJsonStr(errorList)), HttpStatus.OK);
    }

    /**
     * 参数校验拦截器
     * 针对 @RequestBody参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMsg = e.getBindingResult().getAllErrors()
                .stream()
                .map(objectError -> objectError.getDefaultMessage())
                .collect(Collectors.joining(","));
        return new ResponseEntity(Result.createFail(errorMsg), HttpStatus.OK);
    }

    /**
     * 捕获运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Result> handleRuntimeException(RuntimeException ex) {
        GlobalExceptionController.LOG.error(ex.getMessage(), ex);
        return new ResponseEntity(Result.createFail(ex.getMessage()), HttpStatus.OK);
    }

    /**
     * 捕获SQL执行异常
     */
    @ExceptionHandler(SQLException.class)
    public ResponseEntity<Result> handleSQLException(SQLException ex) {
        GlobalExceptionController.LOG.error(ex.getMessage(), ex);
        return new ResponseEntity(Result.createFail(ex.getMessage()), HttpStatus.OK);
    }

    /**
     * 捕获全局异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleAllException(Exception ex) {
        GlobalExceptionController.LOG.error(ex.getMessage(), ex);
        return new ResponseEntity(Result.createFail(ex.getMessage()), HttpStatus.OK);
    }
}
